package com.winning.dps.ds.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @作者： caopengfei
 * @描述: 线程池配置
 * @时间： 2019/4/4
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Autowired
    private Environment env;

    private int corePoolSize = 5;

    private int maxPoolSize = 50;

    private int queueCapacity=1000;

    private String namePrefix="dqmt-check";

    private String configPreFix="async.executor";

    /**
    * @comment： 公共线程池
    * @author： caopengfei
    * @time：  2020/4/23 18:50
    */
    @Bean(name="taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor =  createTaskExecutor("thread");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        return executor;
    }

    private ThreadPoolTaskExecutor createTaskExecutor(String configkey){

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        Integer corePoolSizeTemp =  env.getProperty(configPreFix+"."+configkey+"."+"core_pool_size",Integer.class);
        // 设置核心线程数
        if(corePoolSizeTemp != null){
            corePoolSize = corePoolSizeTemp;
        }
        // 设置最大线程数
        Integer maxPoolSizeTemp =  env.getProperty(configPreFix+"."+configkey+"."+"max_pool_size",Integer.class);
        if(maxPoolSizeTemp != null){
            maxPoolSize = maxPoolSizeTemp;
        }

        Integer queueCapacityTemp =  env.getProperty(configPreFix+"."+configkey+"."+"queue_capacity",Integer.class);
        if(queueCapacityTemp != null){
            queueCapacity = queueCapacityTemp;
        }

        String namePrefixTemp =  env.getProperty(configPreFix+"."+configkey+"."+"name_prefix",String.class);
        if(namePrefixTemp != null){
            namePrefix = namePrefixTemp;
        }
        //设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //设置线程上限
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix(namePrefix);
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //拒绝策略  抛异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }


}
